<template>
  <div >
    <el-row class="resetCalculationForm">
      <el-button icon="el-icon-refresh" type="warning" size="mini" @click="getMixedIngredients">配料数据重置</el-button>
    </el-row>
    <el-row>
      <!--      配料-->
      <el-col :span="7">
        <fieldset>
          <legend>配料</legend>
          <el-table v-loading="loading" :data="batchingCalculationList"
                    :row-class-name="tableRowClassName"
                    @cell-click="tableClick"
                    :cell-style="changeCellStyle2">
            <el-table-column label="原料名称" align="center" prop="rawMaterial"/>
            <el-table-column label="配比（%）" align="center" prop="mixtureRatio" width="90%">
              <template slot-scope="scope">
                <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '配比（%）'">
                  <el-input v-model="scope.row.mixtureRatio" @keyup.enter.native="inputBlur(scope.row)" v-focus
                            @blur="inputBlur(scope.row)">
                  </el-input>
                </span>
                <span v-else>{{ scope.row.mixtureRatio }}</span>
              </template>
            </el-table-column>
            <!--            <el-table-column label="下料量（t/h）" align="center" prop="blankingQuantity">-->
            <!--              <template slot-scope="scope">-->
            <!--                  <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '下料量（t/h）'">-->
            <!--                    <el-input v-model="scope.row.blankingQuantity" @keyup.enter.native="inputBlur(scope.row)" v-focus-->
            <!--                              @blur="inputBlur(scope.row)">-->
            <!--                    </el-input>-->
            <!--                  </span>-->
            <!--                <span v-else>{{ scope.row.blankingQuantity }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="单价（元/t）" align="center" prop="unitPrice">
              <template slot-scope="scope">
                  <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '单价（元/t）'">
                    <el-input v-model="scope.row.unitPrice" @keyup.enter.native="inputBlur(scope.row)" v-focus
                              @blur="inputBlur(scope.row)">
                    </el-input>
                  </span>
                <span v-else>{{ scope.row.unitPrice }}</span>
              </template>
            </el-table-column>
          </el-table>
        </fieldset>
      </el-col>

      <!--    约束条件-->
      <el-col :span="10">
        <fieldset>
          <legend>约束条件</legend>
          <el-table v-loading="loading" :data="batchingCalculationList">
            <el-table-column label="SiO₂" align="center" prop="SiO2"/>
            <el-table-column label="TFe" align="center" prop="TFe"/>
            <el-table-column label="CaO" align="center" prop="CaO"/>
            <el-table-column label="MgO" align="center" prop="MgO"/>
            <el-table-column label="烧损" align="center" prop="fireWaste"/>
            <el-table-column label="水份" align="center" prop="waterPercent"/>
          </el-table>
        </fieldset>
      </el-col>

      <!--    烧结矿化学成分-->
      <el-col :span="7">
        <fieldset>
          <legend>烧结矿化学成分</legend>
          <el-table v-loading="loading" :data="componentResultList"
                    :row-class-name="tableRowClassName" @cell-click="tableClick"
                    :cell-style="changeCellStyle1">
            <el-table-column label="成分" align="center" prop="component"/>
            <el-table-column label="目标值" align="center" prop="aim">
              <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '目标值'">
                      <el-input v-model="scope.row.aim" @keyup.enter.native="inputBlur(scope.row)" v-focus
                                @blur="inputBlur(scope.row)">
                      </el-input>
                    </span>
                <span v-else>{{ scope.row.aim }}</span>
              </template>
            </el-table-column>
            <el-table-column label="计算值" align="center" prop="cal"/>
          </el-table>
        </fieldset>
        <fieldset style="height: 159px">
          <el-form style="padding: 30px">
            <el-form-item label="总下料量：">
              <el-input-number v-model="totalBlankingQuantity" placeholder="请输入总下料量" style="width: 150px"
                               @blur="inputBlur"></el-input-number>
              t
            </el-form-item>
            <el-form-item label="成本：">
              <span style="color: blue">{{sumCost}}</span> 元
            </el-form-item>
          </el-form>
        </fieldset>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {updateChemicalIngredient} from '@/api/app/stock//ingredients'
  import PanThumb from '../../../../components/PanThumb'
  import RightPanel from '../../../../components/RightPanel'
  import Screenfull from '../../../../components/Screenfull'

  import {
    pageCheIngredients,
    getCheIngredients,
    delCheIngredients,
    addCheIngredients,
    updateCheIngredients
  } from '@/api/app/quality/cheIngredients'
  import {
    pageMixIngredients,
    getMixIngredients,
    listMixIngredients,
    delMixIngredients,
    addMixIngredients,
    updateMixIngredients,
  } from '@/api/app/quality/mixIngredients'

  export default {
    components: {Screenfull, RightPanel, PanThumb},
    data() {
      return {
        // 遮罩层
        loading: false,
        calculateFlag: false,
        costOptimization: false,
        tabClickIndex: null,
        tabClickLabel: null,
        calculateTime: null,
        worker: null,
        totalBlankingQuantity: 0,
        priceWeight: 0,
        dealSumPrice: 0,
        sumCost: 0,
        componentResult: {
          calSiO2: null,
          calTFe: null,
          calCaO: null,
          calMgO: null,
          calR: null,
          aimSiO2: null,
          aimTFe: null,
          aimCaO: null,
          aimMgO: null,
          aimR: null
        },
        componentResultList: [
          // {component: 'SiO₂',cal: 0, aim: 4.96 },
          // {component: 'TFe', aim: 57.19 },
          // {component: 'CaO', aim: 9.47 },
          // {component: 'MgO', aim: 2.54 },
          // {component: 'R', aim: 1.91 },
        ],
        batchingCalculationList: [
          //rawMaterial:原料名称, mixtureRatio:配料比, blankingQuantity:下料量 , waterPercent: 水分, SiO2: , fireWaste: 烧损
          // { rawMaterial: '恰那粉', mixtureRatio: 20,  waterPercent: 8.02, SiO2: 3.33, TFe: 65, CaO: 0.03, MgO: 0.15, fireWaste: 3.45, unitPrice: 600},
          // { rawMaterial: '桃 粉', mixtureRatio: 11,  waterPercent: 3.35, SiO2: 8.8, TFe: 52, CaO: 7.97, MgO: 1, fireWaste: 9.15, unitPrice: 550},
          // { rawMaterial: '烧 粉', mixtureRatio: 10, waterPercent: 1, SiO2: 5.5, TFe: 56, CaO: 9.2, MgO: 2.8, fireWaste: 1, unitPrice: 450},
          // { rawMaterial: '混匀矿', mixtureRatio: 15, waterPercent: 10.26, SiO2: 7.63, TFe: 50.8, CaO: 7.1, MgO: 1.5, fireWaste: 4.59, unitPrice: 350},
          // { rawMaterial: '巴 西', mixtureRatio: 17.5, waterPercent: 8, SiO2: 3.74, TFe: 66, CaO: 0.08, MgO: 0.07, fireWaste: 2.6, unitPrice: 400},
          // { rawMaterial: '卡拉斯加', mixtureRatio: 12, waterPercent: 6.5, SiO2: 1.1, TFe: 67, CaO: 0.04, MgO: 0.07, fireWaste: 1.4, unitPrice: 440},
          // { rawMaterial: '煤 粉', mixtureRatio: 3.5, waterPercent: 8, SiO2: 6, CaO: 2, MgO: 1.2, fireWaste: 85, unitPrice: 250},
          // { rawMaterial: '白云石', mixtureRatio: 7, waterPercent: 5, SiO2: 1.2, CaO: 30, MgO: 19.8, fireWaste: 46, unitPrice: 600},
          // { rawMaterial: '石灰石', mixtureRatio: 1, SiO2: 1, CaO: 52, MgO: 1.2, fireWaste: 45, unitPrice: 680},
          // { rawMaterial: '生石灰', mixtureRatio: 3, SiO2: 1.2, CaO: 88, MgO: 1, fireWaste: 15, unitPrice: 51},
        ],
        // 弹出层标题
        title: 'zxjs',
        // 是否显示弹出层
        open: false,
      };
    },

    created() {
      this.getMixedIngredients()
    },

    mounted() {

    },

    methods: {
      getMixedIngredients() {
        listMixIngredients({}).then(response => {
          this.batchingCalculationList = response.data.rows

          pageCheIngredients({}).then(res => {
            this.componentResultList = res.data.rows
            if (this.title === 'zxjs') {
              this.calculate()
              this.updateCheIngredients(this.componentResultList)
            } else {
              this.batchingCalculationList.forEach(function (value, index) {
                value.mixtureRatio = ''
              })
              this.componentResultList.forEach(function (value) {
                value.cal = ''
              })
              this.calMixRatioNoCost()
            }
          })



        })

      },

      updateCheIngredients(componentResultList){
        for(let i = 0;i<componentResultList.length;i++){
          updateCheIngredients(componentResultList[i]).then(res => {
          })
        }

      },



      tableRowClassName({row, rowIndex}) {
        // 把每一行的索引放进row
        row.index = rowIndex
      },

      // tabClick row 当前行 column 当前列
      tableClick(row, column, cell, event) {
        switch (column.label) {
          case '配比（%）':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '下料量（t/h）':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '目标值':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '单价（元/t）':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '配比范围设定':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          default:
            return
        }
      },

      changeCellStyle1(row, column, rowIndex, columnIndex) {
        if (row.column.label === "计算值" || row.column.label === "配比（%）") {
          return 'color: blue'  // 修改的样式
        } else {
          return ''
        }
      },

      changeCellStyle2(row, column, rowIndex, columnIndex) {
        if (row.column.label === "目标值" || row.column.label === "配比（%）") {
          return 'background-color: yellowgreen'  // 修改的样式
        } else {
          return ''
        }
      },

      // 失去焦点初始化
      inputBlur(row) {
        this.tabClickIndex = null
        this.tabClickLabel = ''
        if (this.title === 'zxjs') {
          this.calculate()
          this.updateCheIngredients(this.componentResultList)
        }
      },

      // 配比范围
      verification(row) {
        if (row.ratioMin > row.ratioMax) {
          this.$message.warning("最小值不能大于最大值");
          return false;
        } else if (row.ratioMin < 0 || row.ratioMax > 100) {
          this.$message.warning("配比范围太大")
        } else {
          this.tabClickIndex = null
          this.tabClickLabel = ''
          // this.calMixRatio()
        }
      },

      calMixRatioWithCost() {
        this.calculateFlag = false
        this.costOptimization = true
        setTimeout(() => {
          this.calMixRatio2()
        }, 0)
      },

      calMixRatioNoCost() {
        this.calculateFlag = false
        this.costOptimization = false
        setTimeout(() => {
          this.calMixRatio2()
        }, 0)
      },

      //计算结果
      calculate() {
        // 每一个原料的SiO2成分之和
        let sumBurnResidue = 0
        let sumSiO2 = 0
        let sumTFe = 0
        let sumCaO = 0
        let sumMgO = 0
        let sumCost = 0
        let dealSumPrice = 0
        let dealTotalBlanking
        let totalBlankingQuantity
        if (this.totalBlankingQuantity < 0) {
          dealTotalBlanking = 0
          totalBlankingQuantity = 0
        } else {
          dealTotalBlanking = this.priceWeight / 50000
          totalBlankingQuantity = this.totalBlankingQuantity
        }
        if (!this.batchingCalculationList) {
          return;
        }
        this.batchingCalculationList.forEach(function (value, index, array) {

          if (isNaN(value.waterPercent) && isNaN(value.TFe)) {
            // 干配比
            let dryRatio = value.mixtureRatio
            sumBurnResidue += dryRatio * (100 - value.fireWaste)
            sumSiO2 += value.SiO2 * dryRatio
            sumCaO += value.CaO * dryRatio
            sumMgO += value.MgO * value.mixtureRatio
          } else if (isNaN(value.waterPercent) && !isNaN(value.TFe)) {
            let dryRatio = value.mixtureRatio
            sumBurnResidue += dryRatio * (100 - value.fireWaste)
            sumSiO2 += value.SiO2 * dryRatio
            sumTFe += value.TFe * dryRatio
            sumCaO += value.CaO * dryRatio
            sumMgO += value.MgO * value.mixtureRatio
          } else {
            var dryRatio = value.mixtureRatio * (100 - value.waterPercent) / 100
            sumBurnResidue += dryRatio * (100 - value.fireWaste)
            sumSiO2 += value.SiO2 * dryRatio
            sumTFe += value.TFe * dryRatio
            sumCaO += value.CaO * dryRatio
            sumMgO += value.MgO * value.mixtureRatio
          }
          dealSumPrice += dealTotalBlanking * value.mixtureRatio * value.unitPrice
          sumCost += totalBlankingQuantity * value.mixtureRatio * value.unitPrice / 100
        })
        sumBurnResidue = sumBurnResidue / 100
        let calSiO2 = sumSiO2 / sumBurnResidue
        let calTFe = sumTFe / sumBurnResidue
        let calCaO = sumCaO / sumBurnResidue
        let calMgO = sumMgO / sumBurnResidue
        this.componentResultList[0].cal = calSiO2.toFixed(2);
        this.componentResultList[1].cal = calTFe.toFixed(2);
        this.componentResultList[2].cal = calCaO.toFixed(2);
        this.componentResultList[3].cal = calMgO.toFixed(2);
        if (calSiO2 !== 0) {
          let calR = calCaO / calSiO2
          this.componentResultList[4].cal = calR.toFixed(2);
        } else {
          let calR = 0
          this.componentResultList[4].cal = calR.toFixed(2);
        }
        this.dealSumPrice = dealSumPrice
        this.sumCost = sumCost
      },

      // async calMixRatio(){
      // worker.postMessage()

      // },

      calMixRatio2() {
        let startTime = new Date().getTime()
        let heapArray = []
        let indexArray = []
        let sumLoopTimes = 1
        for (let i = 0; i < this.batchingCalculationList.length; i++) {
          heapArray.push(this.batchingCalculationList[i])
          indexArray.push(0)
        }

        let resArray = []
        let sumObj = {
          sumSiO2: 0,
          sumTFe: 0,
          sumCaO: 0,
          sumMgO: 0,
          sumR: 0,
        }

        // 计算需要开启多少个线程
        // for (let i = 0; i < heapArray.length; i++) {
        //   if (heapArray[i].ratioMax === heapArray[i].ratioMin) continue
        //   sumLoopTimes *= heapArray[i].ratioMax - heapArray[i].ratioMin
        // }
        // let num = Math.round(sumLoopTimes / 20000)

        //开启线程
        //   for (let i = 0; i < heapArray.length; i++){
        //     let ratioDiff = heapArray[i].ratioMax - heapArray[i].ratioMin + 1
        //     let heapMax = apArray[i].ratioMax
        //     if (ratioDiff > num){
        //       let time = ratioDiff / num
        //       heapArray[i].ratioMax = heapArray[i].ratioMin + time - 1
        //       this.$work.run(this.loopMixture(sumObj, heapArray, indexArray, 0, heapArray.length - 1, resArray))
        //       for (let w = 1; w < num -1; w++){
        //         heapArray[i].ratioMin = heapArray[i].ratioMin + time
        //         heapArray[i].ratioMax = heapArray[i].ratioMax + time
        //         this.$work.run(this.loopMixture(sumObj, heapArray, indexArray, 0, heapArray.length - 1, resArray))
        //       }
        //       heapArray[i].ratioMin = heapArray[i].ratioMin + time
        //       heapArray[i].ratioMax = heapMax
        //       this.$work.run(this.loopMixture(sumObj, heapArray, indexArray, 0, heapArray.length - 1, resArray))
        //       break
        //     }
        // }

        // this.worker = this.$worker.create(this.action)
        // this.worker.postMessage('loopMixture',[{sumObj: sumObj}, {heapArray: heapArray}, {indexArray: indexArray}, {heapIndex: 0}, {endIndex: heapArray.length - 1},{resArray: resArray}])
        // this.worker = this.$worker.run(this.loopMixture(sumObj, heapArray, indexArray, 0, heapArray.length - 1, resArray))

        this.loopMixture(sumObj, heapArray, indexArray, 0, heapArray.length - 1, resArray)
        //取最小值
        if (resArray.length > 0) {
          let minRes = resArray[0]
          for (let i = 0; i < resArray.length; i++) {
            if (resArray[i].diff < minRes.diff) {
              minRes = resArray[i]
            }
          }

          for (let i = 0; i < heapArray.length; i++) {
            let mix = minRes.mixArray[i]
            if (!mix) mix = 0
            this.batchingCalculationList[i].mixtureRatio = mix
          }
        } else {
          for (let i = 0; i < heapArray.length; i++) {
            this.batchingCalculationList[i].mixtureRatio = -1
          }
        }
        this.calculate()
        let endTime = new Date().getTime()
        this.calculateTime = endTime - startTime
        this.calculateFlag = true
      },

      // action: [{
      //   message: 'loopMixture',
      loopMixture(sumObj, heapArray, indexArray, heapIndex, endIndex, resArray) {
        if (heapIndex > endIndex) return
        let heap = heapArray[heapIndex]
        let dryRatio
        if (heap.waterPercent > 0) {
          dryRatio = 1 - heap.waterPercent / 100
        } else {
          dryRatio = 0.01
        }

        for (let i = heap.ratioMin; i <= heap.ratioMax; i++) {
          indexArray[heapIndex] = i
          heapArray[heapIndex].mixtureRatio = i
          let sumIndex = 0
          for (let j = 0; j < indexArray.length; j++) {
            sumIndex += indexArray[j]
          }
          if (heapIndex === endIndex && sumIndex === 100) {
            this.calculate()
            let diff = 0
            diff += Math.abs(this.componentResultList[0].cal - this.componentResultList[0].aim)
            diff += Math.abs(this.componentResultList[1].cal - this.componentResultList[1].aim)
            diff += Math.abs(this.componentResultList[2].cal - this.componentResultList[2].aim)
            diff += Math.abs(this.componentResultList[3].cal - this.componentResultList[3].aim)
            diff += Math.abs(this.componentResultList[4].cal - this.componentResultList[4].aim)
            if (this.costOptimization) {
              diff += this.dealSumPrice
            }
            resArray.push({
              diff: diff,
              mixArray: JSON.parse(JSON.stringify(indexArray))
            })
          } else {
            this.loopMixture(sumObj, heapArray, indexArray, heapIndex + 1, endIndex, resArray)
          }
        }
      },
      // }]
    }
  };
</script>
<style scoped>
  .resetCalculationForm {
    text-align: right;
  }

  .warningText {
    text-align: left;
    color: red;
    font-size: 20px;
  }

  .table.air-tank th, .table.air-tank td {
    padding: 6px 2px;
  }

  .row-height {
    height: 40px;
  }
</style>
